package com.strawcom.charmring.ui;

import android.app.Activity;
import android.app.Dialog;
import android.app.NotificationManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.*;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.dialog.suota.DeviceActivity;
import com.google.gson.Gson;
import com.strawcom.charmring.*;
import com.strawcom.charmring.bean.Alert;
import com.strawcom.charmring.bean.Calories;
import com.strawcom.charmring.bean.DailySummary;
import com.strawcom.charmring.bean.Friend;
import com.strawcom.charmring.bean.http.*;
import com.strawcom.charmring.bluetooth.RingBleListActivity;
import com.strawcom.charmring.bluetooth.RingBleService;
import com.strawcom.charmring.bluetooth.RingBleService.LocalBinder;
import com.strawcom.charmring.common.upgrade.UpgradeService;
import com.strawcom.charmring.ui.fragment.ExerciseFragment;
import com.strawcom.charmring.ui.fragment.LocationFragment;
import com.strawcom.charmring.util.*;
import com.strawcom.charmring.util.HttpUtil.ResponeListener;
import com.strawcom.charmring.view.*;
import com.strawcom.charmring.view.SlidingMenu.OnSlidingFinishedListener;
import com.strawcom.charmring.view.SlidingMenu.OnSlidingStateChangedListener;
import org.kymjs.kjframe.KJBitmap;
import org.kymjs.kjframe.utils.DensityUtils;
import org.kymjs.kjframe.widget.RoundImageView;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @ClassName: MainActivity
 * @Description:主activity
 * @author liyongqiang
 * @date 2015-3-30 上午12:02:55
 * 
 */
public class MainActivity extends BaseActivity implements OnClickListener {

	public TitleView titleView;

	private SlidingMenu slidingMenu;

	private RoundImageView imgTitleHead;
	private RoundImageView imgHead;
	private View layoutLocation, layoutSport, layoutCamera;
	private ExerciseFragment exerciseFragment;
	private LocationFragment locationFragment;
	private FragmentManager fragmentManager;
	private TextView viewText;
	private MFrameLayout layContent;
	private View layoutSwitch, layoutAlarmContact, layoutHead, layoutRingBle, layoutAdvice, layoutBuy, layoutBleUpgrade;
	private ImageView imgLocation, imgSport, imgCamera, imgRingState;

	private TextView txRingInfo;
	private RingBleService bleService;

	private TextView txUsername, txUserWeight, txUserHeight;

	public boolean fromPush;

	@Override protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_main);
		super.onCreate(savedInstanceState);
		fromPush = PreferenceUtil.readBoolean(this, C.sp.from_push);
		NotificationManager mNotificationManager = (NotificationManager) App.i().getSystemService(Context.NOTIFICATION_SERVICE);
		mNotificationManager.cancelAll();
		PreferenceUtil.write(this, C.sp.from_push, false);
		initViews();

		com.dialog.suota.data.File.filesDir = context.getExternalFilesDir(null).getPath();
		ableMenuClick(false);

		startRingBleService();
		bindRingBleService();

		uploadExerciseInfo(false); // 上传运动数据

		dlgUploadWaiting = CustomProgressDialog.createDialog(this, false).setMessage(R.string.watting_upload);

		// app 新版本检测
		appUpgradeCheck();
	}

	@Override protected void onResume() {
		super.onResume();
		registerRingMessageReceiver();
		String username = PreferenceUtil.readString(this, C.sp.username);
		int userHeight = PreferenceUtil.readInt(this, C.sp.height);
		float userWieght = PreferenceUtil.readFloat(this, C.sp.weight);
		String headUrl = PreferenceUtil.readString(this, C.sp.headurl);
		if (!TextUtils.isEmpty(username)) {
			txUsername.setText(username);
		}
		if (0 != userHeight) {
			txUserHeight.setText(userHeight + "cm");
		}
		if (0 != userWieght) {
			txUserWeight.setText(userWieght + "kg");
		}
		KJBitmap kjb = KJBitmap.create();
		if (!TextUtils.isEmpty(headUrl)) {
			kjb.display(imgHead, HttpUtil.url_img + headUrl);
			kjb.display(imgTitleHead, HttpUtil.url_img + headUrl);
		}
		else {
			imgHead.setImageResource(R.drawable.head);
			imgTitleHead.setImageResource(R.drawable.head);
		}

		/* 应用切换到前台时如果蓝牙设备服务已经运行 ，对设备需要进行的逻辑操作。 */
		if (bleService != null) {
			final String bleAddress = bleService.getCurrAddress();
			if (!TextUtils.isEmpty(bleAddress)) {
				if (bleService.isCurrConnectionState()) {
					handler.removeCallbacksAndMessages(null);
					handler.postDelayed(new Runnable() {
						@Override public void run() {
							// 重新读取电量信息
							bleService.requestBatteryInfo(bleAddress);		
						}
					}, 1000);
					handler.postDelayed(new Runnable() {
						@Override public void run() {
							// 重新读取运动信息
							bleService.requestExerciseInfo(bleAddress);		
						}
					}, 2000);
				}
				else {
					bleService.connect(bleAddress);
				}
			}
			else {
				txRingInfo.setText(R.string.ring_ble_disconnected);
			}
		}
		
		// 来自于通知的启动
		String info = getIntent().getStringExtra(PushReceiver.EXTRA_POINT);
		if(!TextUtils.isEmpty(info)) {
			showFragment(0);
			final Alert a = new Gson().fromJson(info, Alert.class);
			handler.postDelayed(new Runnable() {
				@Override public void run() {
					locationFragment.showInfoOnMap(a.getName(), a.getMsg(), a.getLat(), a.getLng());		
				}
			}, 300);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		unregisterRingMessageReceiver();
	}

	/** 重新读取运动信息 */
	public void requestExerciseInfo() {
		if (bleService != null) {
			String bleAddress = bleService.getCurrAddress();
			if (!TextUtils.isEmpty(bleAddress)) {
				if (bleService.isCurrConnectionState()) {
					bleService.requestExerciseInfo(bleAddress);
				}
			}
		}
	}

	@Override protected void onDestroy() {
		super.onDestroy();
		unbindRingBleService();


		handler.removeCallbacksAndMessages(null);
	}

	private void initViews() {
		layContent = (MFrameLayout) findViewById(R.id.main_content);

		slidingMenu = (SlidingMenu) findViewById(R.id.main_group);
		SlidingMenuScroller slidingMenuScroller = new SlidingMenuScroller(this);
		slidingMenuScroller.initViewPagerScroll(slidingMenu);
		slidingMenu.setOnSlidingFinishedListener(onToggleFinishedListener);
		slidingMenu.setOnSlidingStateChangedListener(new OnSlidingStateChangedListener() {
			@Override public void onSlidingStart() {
			}

			@Override public void onSlidingOver(boolean isOpened) {
				ableMenuClick(isOpened);
				if(isOpened){
					final float weight = PreferenceUtil.readFloat(MainActivity.this , C.sp.exercise_record_weight);
					txUserWeight.setText(weight + "kg");
				}
			}
		});

		titleView = (TitleView) findViewById(R.id.title_view);
		viewText = (TextView) LayoutInflater.from(this).inflate(R.layout.view_text, null);
		imgTitleHead = new RoundImageView(this);
		android.widget.RelativeLayout.LayoutParams params = new android.widget.RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		params.width = DensityUtils.dip2px(this, 40);
		params.height = DensityUtils.dip2px(this, 40);
		imgTitleHead.setLayoutParams(params);
		imgTitleHead.setImageResource(R.drawable.head);
		imgTitleHead.setOnClickListener(new OnClickListener() {
			@Override public void onClick(View arg0) {
				slidingMenu.toggle();
			}
		});
		titleView.setLeftView(imgTitleHead);

		layoutLocation = findViewById(R.id.layout_location);
		layoutSport = findViewById(R.id.layout_sport);
		layoutCamera = findViewById(R.id.layout_camera);

		layoutLocation.setOnClickListener(this);
		layoutSport.setOnClickListener(this);
		layoutCamera.setOnClickListener(this);

		imgLocation = (ImageView) findViewById(R.id.img_location);
		imgSport = (ImageView) findViewById(R.id.img_sport);
		imgCamera = (ImageView) findViewById(R.id.img_camera);

		imgSport.setImageResource(R.drawable.tab_sport_selected);
		if(C.isEnglish){
			imgLocation.setImageResource(R.drawable.tab_location_en);
			imgSport.setImageResource(R.drawable.tab_sport_selected_en);
			imgCamera.setImageResource(R.drawable.tab_camera_en);
		}     

		imgHead = (RoundImageView) findViewById(R.id.img_head);
		imgHead.setBorderInsideColor(getResources().getColor(R.color.white));
		imgHead.setBorderOutsideColor(getResources().getColor(R.color.red_select));
		imgHead.setBorderThickness(DensityUtils.dip2px(this, 2));
		layoutHead = findViewById(R.id.layout_head);
		layoutHead.setOnClickListener(this);

		layoutSwitch = findViewById(R.id.layout_switch);
		layoutSwitch.setOnClickListener(this);
		layoutAlarmContact = findViewById(R.id.layout_alarm_contact);
		layoutAlarmContact.setOnClickListener(this);

		layoutRingBle = findViewById(R.id.layout_ring_ble);
		layoutRingBle.setOnClickListener(this);
		txRingInfo = (TextView) findViewById(R.id.tx_ring_info);

		layoutAdvice = findViewById(R.id.layout_advice);
		layoutAdvice.setOnClickListener(this);

		layoutBuy = findViewById(R.id.layout_buy);
		layoutBuy.setOnClickListener(this);
		
		layoutBleUpgrade = findViewById(R.id.layout_ble_upgrade);
		layoutBleUpgrade.setOnClickListener(this);
		
		findViewById(R.id.btn_logout).setOnClickListener(this);
		txUsername = (TextView) findViewById(R.id.tx_name);
		txUserWeight = (TextView) findViewById(R.id.tx_weight);
		txUserHeight = (TextView) findViewById(R.id.tx_height);

		imgRingState = (ImageView) findViewById(R.id.img_ele);

		fragmentManager = getSupportFragmentManager();
		FragmentTransaction ft = fragmentManager.beginTransaction();
		List<Fragment> addedFragments = fragmentManager.getFragments();
		if (addedFragments != null) {
			for (Fragment fragment : addedFragments) {
				if (fragment != null) {
					ft.remove(fragment);
				}
			}
		}
		ft.commit();
		if (fromPush) {
			showFragment(0);
		}
		else {
			showFragment(1);
		}
	}

	private OnSlidingFinishedListener onToggleFinishedListener = new OnSlidingFinishedListener() {
		@Override public void onFinished(boolean isOpen) {
			layContent.setIntercept(isOpen);
		}
	};

	@Override public void onClick(View view) {
		switch (view.getId()) {
		case R.id.layout_location:
			showFragment(0);
			break;
		case R.id.layout_sport:
			showFragment(1);
			break;
		case R.id.layout_camera:
			actionStart(net.sourceforge.opencamera.MainActivity.class);
			break;
		case R.id.layout_head:
			startActivity(new Intent(this, UserInfoActivity.class));
			break;
		case R.id.layout_switch:
			actionStart(SwitchActivity.class);
			break;
		case R.id.layout_alarm_contact:
			actionStart(AlarmActivity.class);
			break;
		case R.id.layout_ring_ble:
			connectRingBluetooth();
			break;
		case R.id.layout_advice:
			actionStart(AdviceActivity.class);
			break;
		case R.id.btn_logout:
			showLogoutDialog();
			break;
		case R.id.layout_buy:
			openBrowser(C.app.download_url);
			break;
		case R.id.layout_ble_upgrade:
//			BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
//			String address = PreferenceUtil.readString(this, C.sp.ring_ble_address, "");
			BluetoothDevice device = null;
			try {
//				device = bluetoothManager.getAdapter().getRemoteDevice(address);
				device = bleService.getDevice();
			} catch (Exception e) {
				e.printStackTrace();
			}

			Intent i = new Intent(MainActivity.this, DeviceActivity.class);
			i.putExtra("device", device);
			startActivity(i);
//			actionStart(RingBleUpgradeActivity.class);
			break;
		}
	}

	public void showFragment(int position) {
		imgLocation.setImageResource(R.drawable.tab_location);
		imgSport.setImageResource(R.drawable.tab_sport);
		if(C.isEnglish){
			imgLocation.setImageResource(R.drawable.tab_location_en);
			imgSport.setImageResource(R.drawable.tab_sport_en);
		}

		FragmentTransaction transaction = fragmentManager.beginTransaction();
		if (exerciseFragment != null) {
			transaction.hide(exerciseFragment);
		}
		if (locationFragment != null) {
			transaction.hide(locationFragment);
		}

		if (position == 0) {
			if (locationFragment == null) {
				locationFragment = new LocationFragment();
				transaction.add(R.id.content_view, locationFragment);
			}
			else {
				transaction.show(locationFragment);
			}
			titleView.setCenterView(viewText);
			titleView.layoutRight.removeAllViews();
			imgLocation.setImageResource(R.drawable.tab_location_selected);
			if(C.isEnglish){
				imgLocation.setImageResource(R.drawable.tab_location_selected_en);
			}
		}
		if (position == 1) {
			if (exerciseFragment == null) {
				exerciseFragment = new ExerciseFragment();
				transaction.add(R.id.content_view, exerciseFragment);
			}
			else {
				transaction.show(exerciseFragment);
			}
			exerciseFragment.resetTitle();
			imgSport.setImageResource(R.drawable.tab_sport_selected);
			if(C.isEnglish){
				imgSport.setImageResource(R.drawable.tab_sport_selected_en);
			}
		}
		transaction.commit();
	}

	private long exitTime = 0;

	@Override public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - exitTime) > 2000) {
				Toast.makeText(getApplicationContext(), R.string.exit_app_tip, Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
			}
			else {
				ActivityCollector.finishAll();

				bleService.stopIfDisconnect();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void ableMenuClick(boolean able) {
		layoutHead.setOnClickListener(able ? this : null);
		layoutSwitch.setOnClickListener(able ? this : null);
		layoutAlarmContact.setOnClickListener(able ? this : null);
		layoutRingBle.setOnClickListener(able ? this : null);
		layoutAdvice.setOnClickListener(able ? this : null);
		layoutBuy.setOnClickListener(able ? this : null);
		layoutBleUpgrade.setOnClickListener(able ? this : null);
	}

	public SlidingMenu getSlidingMenu() {
		return slidingMenu;
	}

	private void connectRingBluetooth() {
		if (bleService == null) {
			LogUtil.e("ring ble servcice not running");
			return;
		}
		if (!bleService.isEnable()) {
			Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableBtIntent, C.app.requestCode_enable_ring_bluetooth);
		}
		else {
			actionStart(RingBleListActivity.class);
		}
	}

	@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == C.app.requestCode_enable_ring_bluetooth && resultCode == Activity.RESULT_OK) {
			return;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void startRingBleService() {
		Intent intent = new Intent(this, RingBleService.class);
		startService(intent);
	}

	private void bindRingBleService() {
		Intent intent = new Intent(this, RingBleService.class);
		bindService(intent, conn, BIND_AUTO_CREATE);
	}

	private void unbindRingBleService() {
		unbindService(conn);
	}

	private final ServiceConnection conn = new ServiceConnection() {
		@Override public void onServiceDisconnected(ComponentName name) {
			LogUtil.e("MainActivity onServiceDisconnected()");
			bleService = null;
		}

		@Override public void onServiceConnected(ComponentName name, IBinder service) {
			LogUtil.e("MainActivity onServiceConnected()");
			bleService = ((LocalBinder) service).getService();
			if (!bleService.isEnable()) {
				Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(enableBtIntent, C.app.requestCode_enable_ring_bluetooth);
			}
			else {
				String lastAddress = bleService.getCurrAddress();
				if (lastAddress != null && !bleService.isCurrConnectionState()) {
					bleService.connect(lastAddress);
				}
				else {
					handler.postDelayed(runRequestBattery, 1000);
				}
			}
		}
	};

	private void registerRingMessageReceiver() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(RingBleService.ACTION_GATT_CONNECTED);
		filter.addAction(RingBleService.ACTION_GATT_DISCONNECTED);
		filter.addAction(RingBleService.ACTION_GATT_BATTERY_INFO);
		filter.addAction(RingBleService.ACTION_GATT_MOTION_ALARM);
		filter.addAction(RingBleService.ACTION_GATT_UNKOWN_INFO);

		registerReceiver(ringMessageReceiver, filter);
	}

	private void unregisterRingMessageReceiver() {
		unregisterReceiver(ringMessageReceiver);
	}

	private Handler handler = new Handler();
	private Runnable runRequestBattery = new Runnable() {
		@Override public void run() {
			if (bleService != null && txRingInfo.getTag() == null) {
				String bleAddress = bleService.getCurrAddress();
				if (!TextUtils.isEmpty(bleAddress)) {
					bleService.requestBatteryInfo(bleService.getCurrAddress());
					handler.postDelayed(runRequestBattery, 5000);
				}
			}
		}
	};

	private final BroadcastReceiver ringMessageReceiver = new BroadcastReceiver() {
		@Override public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (RingBleService.ACTION_GATT_CONNECTED.equals(action)) {
				txRingInfo.setText(R.string.ring_ble_connected);
				handler.postDelayed(runRequestBattery, 4000);
				imgRingState.setImageResource(R.drawable.ic_left_menu_ring_connected);
			}
			else if (RingBleService.ACTION_GATT_DISCONNECTED.equals(action)) {
				txRingInfo.setText(R.string.ring_ble_disconnected);
				handler.removeCallbacks(runRequestBattery);
				txRingInfo.setTag(null);
				imgRingState.setImageResource(R.drawable.ic_left_menu_ring_disconnected);
			}
			else if (RingBleService.ACTION_GATT_MOTION_ALARM.equals(action)) {
				String s = PreferenceUtil.readString(MainActivity.this, C.sp.alarm_msg_info);
				String msg = "";
				String frind = "";
				if (!TextUtils.isEmpty(s)) { // 本地存在告警消息设置
					PostEmergencyConfigRequest pcr = new Gson().fromJson(s, PostEmergencyConfigRequest.class);
					if (pcr.contactlist != null && pcr.contactlist.size() > 0) {
						for (Friend f : pcr.contactlist) {
							frind += "," + f.name;
						}
						frind = "[" + frind.substring(1) + "]";
					}
					msg = "[" + pcr.msg + "]";
				}
				String showS = "已将告警消息" + msg + "发送至好友" + frind;
				showToast(showS);
			}
			else if (RingBleService.ACTION_GATT_BATTERY_INFO.equals(action)) {
				handler.removeCallbacks(runRequestBattery);
				int battery = intent.getIntExtra(RingBleService.EXTRA_DATA, 101);

				if (battery >= 0 && battery <= 100) {
					String info = String.format(getString(R.string.ring_ble_connected_2), battery) + "%";
					txRingInfo.setText(info);
					txRingInfo.setTextColor(battery <= 20 ? 0xfff67b33 : 0xff333333);
					txRingInfo.setTag(battery);
				}
			}
			else if (RingBleService.ACTION_GATT_UNKOWN_INFO.equals(action)) {
				String unkownA = intent.getStringExtra(RingBleService.EXTRA_DATA);
				if (RingBleService.ACTION_GATT_BATTERY_INFO.equals(unkownA)) {
					handler.removeCallbacks(runRequestBattery);
					// txRingInfo.setText(R.string.ring_ble_info2);
				}
			}
		}
	};

	private void uploadExerciseInfo(boolean inculdeToday) {
		uploadExerciseDetailInfo(inculdeToday);
		uploadExerciseSummaryInfo(inculdeToday);
	}

	private void uploadExerciseDetailInfo(boolean inculdeToday) {
		String where = inculdeToday ? "syncflag2 == ? and date <= ?" : "syncflag2 == ? and date < ?";
		final List<DailySummary> uploadList = DataSupport.where(where, "0", App.i().today).find(DailySummary.class);
		if (uploadList == null || uploadList.size() < 1) return;

		final List<ExerciseDetailRequest.DailySummaryRequest> dl = new ArrayList<ExerciseDetailRequest.DailySummaryRequest>();
		for (DailySummary dailySummary : uploadList) {
			ExerciseDetailRequest.DailySummaryRequest d = ExerciseDetailRequest.DailySummaryRequest.convertByDailySummary(dailySummary);
			dl.add(d);
		}

		ExerciseDetailRequest request = new ExerciseDetailRequest();
		request.msgid = "POST_EVERYDAY_DETAIL";
		request.everyday_detail_tbl = dl;

		HttpUtil.requestJson(Method.POST, request, new ResponeListener() {
			@Override public void onResponse(BaseResponse response, String resultStr) {
				LogUtil.e("运动明细同步上传成功");
				for (DailySummary dailySummary : uploadList) {
					dailySummary.setSyncflag2(true);
					dailySummary.update(dailySummary.getId());
				}

				if (logout) {
					dlgUploadWaiting.dismiss();
					flagDetail2 = true;
					clearAllData(false);
				}
			}

			@Override public void onErrorResponse(Exception error) {
				LogUtil.e("运动明细同步上传失败");
				if (logout) {
					dlgUploadWaiting.dismiss();
					showToast(R.string.exit_fail);
				}
			}
		});
	}

	private void uploadExerciseSummaryInfo(boolean inculdeToday) {
		String where = inculdeToday ? "syncflag1 == ? and date <= ?" : "syncflag1 == ? and date < ?";
		final List<DailySummary> uploadList = DataSupport.where(where, "0", App.i().today).find(DailySummary.class);
		if (uploadList == null || uploadList.size() < 1) return;

		final List<ExerciseRequest.DailySummaryRequest> dl = new ArrayList<ExerciseRequest.DailySummaryRequest>();
		for (DailySummary dailySummary : uploadList) {
			ExerciseRequest.DailySummaryRequest d = ExerciseRequest.DailySummaryRequest.convertByDailySummary(dailySummary);
			dl.add(d);
		}

		ExerciseRequest request = new ExerciseRequest();
		request.msgid = "POST_EVERYDAY_SUMMARY";
		request.everyday_summary_tbl = dl;

		HttpUtil.requestJson(Method.POST, request, new ResponeListener() {

			@Override public void onResponse(BaseResponse response, String resultStr) {
				LogUtil.e("运动总汇同步上传成功");
				for (DailySummary dailySummary : uploadList) {
					dailySummary.setSyncflag1(true);
					dailySummary.update(dailySummary.getId());
				}

				if (logout) {
					dlgUploadWaiting.dismiss();
					flagSummary1 = true;
					clearAllData(false);
				}
			}

			@Override public void onErrorResponse(Exception error) {
				LogUtil.e("运动总汇同步上传失败");
				if (logout) {
					dlgUploadWaiting.dismiss();
					showToast(R.string.exit_fail);
				}
			}
		});
	}

	private Dialog dlgLogout;

	private void showLogoutDialog() {
		if (dlgLogout != null) {
			dlgLogout.show();
			return;
		}

		TextView content = (TextView) LayoutInflater.from(context).inflate(R.layout.dialog_simple_text, null);
		content.setText(R.string.logout_tip);
		dlgLogout = DialogUtil.init(this).create(content, true, true).setConfirmListener(new OnClickListener() {
			@Override public void onClick(View v) {
				logout();
				dlgLogout.dismiss();
			}
		}).setCancelListener(new OnClickListener() {
			@Override public void onClick(View v) {
				dlgLogout.dismiss();

				clearAllData(true);
			}
		}).show();
	}

	private void logout() {
		
		dlgUploadWaiting.show();
		logout = true;
		uploadExerciseInfo(true);
	}

	private boolean logout = false;
	private boolean flagSummary1 = false;
	private boolean flagDetail2 = false;
	private CustomProgressDialog dlgUploadWaiting;

	private void clearAllData(boolean mandatory) {
		if (logout && flagSummary1 && flagDetail2 || mandatory) {
			PreferenceUtil.clean(MainActivity.this);
			DataSupport.deleteAll(Alert.class);
			DataSupport.deleteAll(Calories.class);
			DataSupport.deleteAll(DailySummary.class);
		}

		dlgUploadWaiting.dismiss();
		actionStart(LoginActivity.class);
		finish();
	}

	/** 应当在onCreate的时候被调用，用于默默地检测app是否有新版本*/
	private void appUpgradeCheck(){
		AppVersionCheckRequest request = new AppVersionCheckRequest();
		request.msgid = C.request_megid_post_app_version_code;
		request.versioncode = BaseUtil.getAppVersion(this);

		HttpUtil.requestJson(Method.POST, request, new ResponeListener() {
			@Override public void onResponse(BaseResponse response, String resultStr) {
				if(response.retcode != 0){
					// 弹出框提示升级
					AppVersionCheckResponse resp= HttpUtil.gson.fromJson(resultStr, AppVersionCheckResponse.class);
					showUpgradeDialog( resp.versionurl, resp.versionmsg);
					LogUtil.e("APP 版本检测  -可以升级");
				}else{
					LogUtil.e("APP 版本检测  -最新版本");	
				}
				
			}

			@Override public void onErrorResponse(Exception error) {
				LogUtil.e("APP 版本检测失败");
			}
		});
	}
	
	private Dialog dlgUpVersion;
	
	private void showUpgradeDialog(final String upUrl, String upMessage){
		if (dlgUpVersion != null){
			try {
				if(!dlgUpVersion.isShowing()) dlgUpVersion.show();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return;
		}

		try {
			TextView content = (TextView) LayoutInflater.from(context).inflate(R.layout.dialog_simple_text, null);
			content.setText(upMessage);
			dlgUpVersion = DialogUtil.init(this).create(content, true, true).setTitleText(R.string.upgrade_tip)
					.setConfirmListener(new OnClickListener() {
				@Override public void onClick(View v) {
					Intent intent = new Intent(MainActivity.this, UpgradeService.class);
					intent.putExtra("Key_App_Name", getString(R.string.app_name));
					intent.putExtra("Key_Down_Url", HttpUtil.url_app_update + upUrl);
					startService(intent);
					
					dlgUpVersion.dismiss();
				}
			}).setCancelListener(new OnClickListener() {
				@Override public void onClick(View v) {
					dlgUpVersion.dismiss();
				}
			}).show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
